package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.yaml.snakeyaml.events.Event;


import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements  ILock {

    private String name;
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private  static final String KEY_PREFIC="lock:";
    //线程id
    private static final String ID_PREFIX= UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.luo"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIC+name, threadId, timeoutSec, TimeUnit.SECONDS);
        //直接返回success有个拆箱过程 假设success是null的话 会造成空指针异常
        return Boolean.TRUE.equals(success);
    }
    @Override
    public void unlock() {
       //调用luo脚本
        stringRedisTemplate.execute(
                //锁的脚本
                UNLOCK_SCRIPT,
                //锁的key名
                Collections.singletonList(KEY_PREFIC+name),
                //线程名
                ID_PREFIX+Thread.currentThread().getId());
    }
 /*   @Override
    public void unlock() {
        //获取线程id
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        //获取锁中的表示
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIC + name);
        //判断是否一致
        if (threadId.equals(id)){
            stringRedisTemplate.delete(KEY_PREFIC+name);
        }

    }*/
}
